﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.ComponentModel;

namespace TaskManager
{
    /// <summary>
    /// Writes all processes into a xml file
    /// </summary>
    public class ProcessToXml
    {
        private XmlSerializer s = null;
        private Type type = null;


        public ProcessToXml()
        {
            this.type = typeof(ProcessRetriever);
            try
            {
                this.s = new XmlSerializer(this.type);
            }
            catch (Win32Exception e) { }

        }

        public XmlDocument Serialize(ProcessRetriever rootclass)
        {
            string xml = StringSerialize(rootclass);
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(xml);
            return doc;
        }

        private string StringSerialize(ProcessRetriever rootclass)
        {
            TextWriter w = WriterSerialize(rootclass);
            string xml = w.ToString();
            w.Close();
            return xml.Trim();
        }

        private TextWriter WriterSerialize(ProcessRetriever rootclass)
        {
            TextWriter w = new StringWriter();
            this.s = new XmlSerializer(this.type);
            s.Serialize(w, rootclass);
            w.Flush();
            return w;
        }
        public static bool WriteFile(string file, ProcessRetriever config)
        {
            bool ok = false;
            ProcessToXml serializer = new ProcessToXml();
            try
            {
                string xml = serializer.Serialize(config).OuterXml;
                using (StreamWriter writer = new StreamWriter(file, false))
                {
                    writer.Write(xml.Trim());
                    writer.Flush();
                    writer.Close();
                }
                ok = true;
            }
            catch { }
            return ok;
        }

    }
}
